package org.example.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Description: JWT 拦截器
 * @Author: 曹震
 * @Date: 2024/11/23 15:48
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        // 排除登录和注册接口
        if (requestURI.equals("/ssm/user/login") || requestURI.equals("/ssm/user/register")) {
            return true;  // 放行，不进行Token验证
        }

        // 从请求头中获取 Authorization 字段
        String token = request.getHeader("Authorization");

        // 检查 Token 是否存在
        if (token == null || token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Authorization token is missing");
            return false;
        }

        // 去除 Bearer 前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        try {
            // 解析 Token
            Jws<Claims> claims = org.example.utils.JwtToken.parseToken(token);

            // 检查 Token 是否过期
            if (org.example.utils.JwtToken.isTokenExpired(token)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("Token has expired");
                return false;
            }

            // 检查 Token 是否即将过期
            if (org.example.utils.JwtToken.isTokenExpiringSoon(claims.getPayload())) {
                // 延长 Token 有效期
                String newToken = org.example.utils.JwtToken.extendTokenExpiration(claims.getPayload());
                // 将新 Token 放入响应头
                response.setHeader("Authorization", "Bearer " + newToken);
            }

            // 如果 Token 有效，继续处理请求
            return true;
        } catch (JwtException e) {
            // Token 无效或解析错误
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Invalid token");
            return false;
        }
    }
}